package excel

import (
	"fmt"
	"log"
	"os"
	"strconv"
	"time"

	"github.com/360EntSecGroup-Skylar/excelize/v2"
	"github.com/gogf/gf/database/gdb"
	_ "image/gif"
	_ "image/jpeg"
	_ "image/png"
)
//中文文档https://xuri.me/excelize/zh-hans/base/installation.html#image
// 下载Excel
func NewDownlaodExcel(heads, key []string, data gdb.Result) (string, error) {
	// 创建路径
	curDir, err := os.Getwd()

	if err != nil {
		return "", err
	}
	curdate := time.Now().UnixNano()
	filename := strconv.FormatInt(curdate, 10) + ".xlsx"

	filePath := curDir + "/public/upload/" + filename

	err = CreateFilePath(filePath)
	if err != nil {
		log.Printf("%s", err.Error())
		return "", err
	}

	// 创建文件
	newfile := excelize.NewFile()
	// 添加新工作表
	index := newfile.NewSheet("Sheet1")
	Slice := []string{"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O",
		"P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"}
	// 头部写入
	for k, head := range heads {
		newfile.SetColWidth("Sheet1","D","D",20)
		err := newfile.SetCellValue("Sheet1", fmt.Sprintf("%s%d", Slice[k], 1), head)
		if err != nil {
			fmt.Println(err)
		}
	}

	// 主体写入数据
	for k, record := range data {
		newfile.SetRowHeight("Sheet1", k+2, 50)
		for k1, v := range key {
			if v == "image" {
				if !record["image"].IsEmpty() {
					if err := newfile.AddPicture("Sheet1", fmt.Sprintf("%s%d", "D", k+2), fmt.Sprintf("%s%s", curDir+"/public", record["image"].String()), `{"x_scale": 0.3, "y_scale": 0.3, "positioning": "oneCell", "locked": true}`); err != nil {
						fmt.Println(err)
					}
				}
			} else {
				newfile.SetCellValue("Sheet1", fmt.Sprintf("%s%d", Slice[k1], k+2), record[v])
			}

		}
	}
	// 在提供的路径中将文件保存到xlsx文件
	newfile.SetActiveSheet(index)
	if err := newfile.SaveAs(filePath); err != nil {
		fmt.Println(err)
	}
	return filename, nil
}
